import NProgress from "nprogress";
import "nprogress/nprogress.css";
import Vue from "vue";
import VueRouter from "vue-router";
import modules from "./modules";
import { storeExtend } from "@/store";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [...modules]
});
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (!Vue.$islogin() && to.meta.nologin != true) {
    next({
      path: "/login",
      query: {
        redirect_uri: to.fullPath
      }
    });
    NProgress.done();
  } else if (storeExtend.state.loginUser == null && to.meta.nologin != true) {
    Vue.$getlogin()
      .then(v => {
        if (v != null) {
          Vue.$signCookie(v.authorization);
          storeExtend.commit.commitLoginUser(v.user);
          next();
          NProgress.done();
          return;
        } else {
          next({
            path: "/login",
            params: {
              redirect_uri: to.path
            }
          });
        }

        NProgress.done();
        return;
      })
      .catch(e => {
        //拉取失败 跳转到登录
        next({
          path: "/login",
          params: {
            redirect_uri: to.path
          }
        });
        NProgress.done();
        return;
      });
  }
  next();
  NProgress.done();
});
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

export default router;
